package com.laisheng.interview.controller;

import com.laisheng.interview.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 邮件发送控制器
 */
@Slf4j
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class MailController {

    @Autowired
    private MailService mailService;

    /**
     * 发送邮件
     * @param mailRequest 邮件请求参数
     * @return 发送结果
     */
    @PostMapping("/sendMail")
    public Map<String, Object> sendMail(@RequestBody Map<String, String> mailRequest) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String to = mailRequest.get("to");
            String subject = mailRequest.get("subject");
            String content = mailRequest.get("content");
            
            // 参数验证
            if (to == null || to.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "收件人邮箱不能为空");
                return result;
            }
            
            if (subject == null || subject.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "邮件主题不能为空");
                return result;
            }
            
            if (content == null || content.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "邮件内容不能为空");
                return result;
            }
            
            // 发送邮件
            boolean success = mailService.sendSimpleMail(to, subject, content);
            
            if (success) {
                result.put("success", true);
                result.put("message", "邮件发送成功");
                log.info("邮件发送成功，收件人: {}, 主题: {}", to, subject);
            } else {
                result.put("success", false);
                result.put("message", "邮件发送失败");
                log.error("邮件发送失败，收件人: {}, 主题: {}", to, subject);
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "邮件发送异常: " + e.getMessage());
            log.error("邮件发送异常", e);
        }
        
        return result;
    }
} 